<template>
  <view class="vip-center">
    <!-- VIP套餐选择 -->
    <view class="vip-section">
      <view class="vip-header">
        <view class="vip-title-wrap">
          <text class="vip-title">开通VIP</text>
          <image class="vip-title-bg" src="/static/images/bg-vip-title.png" mode="widthFix"></image>
        </view>
      </view>
      
      <view class="vip-plans">
        <view class="plan-item" 
              v-for="(plan, index) in vipPlans" 
              :key="index"
              :class="{ active: selectedPlan === index, popular: plan.popular }"
              @click="selectPlan(index)">
          <view class="plan-duration">
            <text>{{ plan.duration }}</text>
          </view>
          <view class="plan-price">
            <text class="price-symbol">¥</text>
            <text class="price-value">{{ plan.price }}</text>
          </view>
          <view class="plan-desc">
            <text>每天仅需￥{{ getDailyPriceText(plan) }}</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 会员权益 -->
    <view class="benefits-section">
      <view class="vip-header">
        <view class="vip-title-wrap">
          <text class="vip-title">会员权益</text>
          <image class="vip-title-bg" src="/static/images/bg-vip-title.png" mode="widthFix"></image>
        </view>
      </view>
      
      <view class="benefits-grid">
        <view class="benefit-item" v-for="(benefit, index) in vipBenefits" :key="index">
          <view class="benefit-icon">
            <image :src="benefit.icon" mode="aspectFit" class="benefit-image"></image>
          </view>
          <text class="benefit-title">{{ benefit.title }}</text>
        </view>
      </view>
    </view>
    
    <!-- 会员 -->
    <view class="recent-vips">
      <view class="vip-header">
        <view class="vip-title-wrap">
          <text class="vip-title">会员</text>
          <image class="vip-title-bg" src="/static/images/bg-vip-title.png" mode="widthFix"></image>
        </view>
      </view>
      
      <view class="vips-list">
        <view 
          v-for="(vip, index) in displayedVips" 
          :key="index" 
          class="vip-item"
        >
          <image class="vip-avatar" :src="vip.avatar" mode="aspectFill"></image>
          <view class="vip-info">
            <text class="vip-message">恭喜会员 {{ maskName(vip.name) }} 成功充值 <text class="vip-plan-highlight">{{ vip.plan }}</text></text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 购买按钮 -->
    <view class="purchase-section">
      <view class="selected-plan-info">
        <text class="selected-text">实付：</text>
        <text class="selected-price">￥{{ vipPlans[selectedPlan].price }}</text>
      </view>
      <view class="purchase-btn" @click="purchaseVip">
        <text>立即支付</text>
      </view>
    </view>
  </view>
</template>

<script>
/**
 * VIP中心页面
 * @author 王勇程 <laughskydragon@qq.com>
 */
import { getVipPackages, getRecentVipUsers, createVipOrder, requestPayment } from '@/api/vip'

export default {
  name: 'VipCenter',
  data() {
    return {
      selectedPlan: 1, // 默认选择年度套餐
      vipPlans: [
        {
          duration: '三年VIP',
          price: 599,
          originalPrice: 1044,
          description: '平均每月仅需16.6元',
          popular: false
        },
        {
          duration: '年度VIP',
          price: 299,
          originalPrice: 348,
          description: '平均每月仅需24.9元',
          popular: true
        },
        {
          duration: '月度VIP',
          price: 29,
          originalPrice: null,
          description: '体验VIP专属服务',
          popular: false
        }
      ],
      vipBenefits: [
        {
          icon: '/static/images/full-information-inquiry.png',
          color: '#FFF',
          title: '全信息查阅',
          description: '全信息查阅'
        },
        {
          icon: '/static/images/unlimited-functionality.png',
          color: '#FFF',
          title: '功能无限制',
          description: '功能无限制'
        },
        {
          icon: '/static/images/feedback-prioritization.png',
          color: '#FFF',
          title: '反馈优先处理',
          description: '反馈优先处理'
        },
        {
          icon: '/static/images/no-ads.png',
          color: '#FFF',
          title: '无广告',
          description: '无广告'
        }
      ],
      recentVips: [
        {
          name: '用户***1234',
          avatar: '/static/images/default-avatar.png',
          time: '刚刚',
          plan: '年度VIP'
        },
        {
          name: '用户***5678',
          avatar: '/static/images/default-avatar.png',
          time: '2分钟前',
          plan: '三年VIP'
        },
        {
          name: '用户***9012',
          avatar: '/static/images/default-avatar.png',
          time: '5分钟前',
          plan: '月度VIP'
        },
        {
          name: '用户***3456',
          avatar: '/static/images/default-avatar.png',
          time: '8分钟前',
          plan: '年度VIP'
        },
        {
          name: '用户***7890',
          avatar: '/static/images/default-avatar.png',
          time: '12分钟前',
          plan: '三年VIP'
        }
      ],
      displayedVips: [], // 用于动态显示的用户列表
      vipDisplayTimer: null // 定时器
    }
  },
  
  onLoad() {
    this.loadVipData()
    this.loadRecentVips()
    this.startVipAnimation()
  },
  
  onUnload() {
    // 清除定时器
    if (this.vipDisplayTimer) {
      clearInterval(this.vipDisplayTimer)
    }
  },
  methods: {
    // 选择套餐
    selectPlan(index) {
      this.selectedPlan = index
    },
    
    // 加载VIP数据
    async loadVipData() {
      try {
        const res = await getVipPackages()
        let packages = []
        packages = res
        console.log('VIP套餐列表:', packages)
        if (packages.length) {
          this.vipPlans = packages.map(item => ({
            id: item.id,
            duration: item.name || item.type_name,
            price: parseFloat(item.price),
            originalPrice: item.original_price ? parseFloat(item.original_price) : null,
            description: item.description || '',
            popular: !!item.is_recommended,
            durationDays: item.duration_days || 0
          }))
          const yearIndex = this.vipPlans.findIndex(p => /年/.test(p.duration))
          this.selectedPlan = yearIndex >= 0 ? yearIndex : 0
        }
      } catch (error) {
        console.error('加载VIP数据失败:', error)
      }
    },
    getDailyPriceText(plan) {
      const price = parseFloat(plan.price || 0)
      let days = parseInt(plan.durationDays || plan.duration_days || 0)
      if (!days) {
        const name = String(plan.duration || '')
        if (name.indexOf('三年') !== -1) days = 1095
        else if (name.indexOf('年') !== -1) days = 365
        else days = 30
      }
      if (!price || !days) return ''
      const val = Math.round((price / days) * 10) / 10
      return (val % 1 === 0) ? val.toFixed(0) : val.toFixed(1)
    },
    
    // 加载最近开通VIP（仅第一页）
    async loadRecentVips() {
      try {
        const response = await getRecentVipUsers({ page: 1, limit: 10 })
        if (response.code === 0) {
          this.recentVips = response.data.users || this.recentVips
        }
      } catch (error) {
        console.error('加载最近VIP失败:', error)
      }
    },
    maskName(name) {
      const str = String(name || '')
      if (!str) return ''
      if (str.indexOf('*') !== -1) return str
      if (str.length <= 1) return str
      const first = str[0]
      const last = str[str.length - 1]
      return `${first}*${last}`
    },
    
    // 开始VIP用户动画显示
    startVipAnimation() {
      let currentIndex = 0
      
      // 先显示第一个用户
      if (this.recentVips.length > 0) {
        this.displayedVips = [this.recentVips[0]]
        currentIndex = 1
      }
      
      // 每3秒添加一个新用户，营造信息流效果
      this.vipDisplayTimer = setInterval(() => {
        if (currentIndex < this.recentVips.length) {
          // 在列表顶部添加新用户
          this.displayedVips.unshift(this.recentVips[currentIndex])
          currentIndex++
          
          // 限制显示的用户数量，保持列表不会太长
          if (this.displayedVips.length > 8) {
            this.displayedVips.pop()
          }
        } else {
          // 所有用户都显示完后，重新开始循环
          currentIndex = 0
          // 重新开始时，保留当前显示的用户，继续添加
          if (this.recentVips.length > 0) {
            this.displayedVips.unshift(this.recentVips[0])
            currentIndex = 1
            
            // 限制显示的用户数量
            if (this.displayedVips.length > 8) {
              this.displayedVips.pop()
            }
          }
        }
      }, 3000)
    },
    
    // 购买VIP
    async purchaseVip() {
      const selectedPlanData = this.vipPlans[this.selectedPlan]
      try {
        await this.processPayment(selectedPlanData, 'wechat')
      } catch (error) {
        console.error('购买VIP失败:', error)
        uni.showToast({ title: '购买失败', icon: 'none' })
      }
    },
    
    // 处理支付
    async processPayment(planData, paymentMethod) {
      try {
        const orderResp = await createVipOrder({ package_id: planData.id })
        if (!orderResp || !orderResp.order_no || !orderResp.payment_params) {
          throw new Error('创建订单失败或支付参数缺失')
        }
        await uni.requestPayment({ provider: 'wxpay', ...orderResp.payment_params })
        uni.showModal({
          title: '支付成功',
          content: `恭喜您成功开通${planData.duration}！`,
          showCancel: false,
          success: () => { uni.navigateBack() }
        })
      } catch (error) {
        console.error('支付处理失败:', error)
        uni.showToast({ title: error.message || '支付失败', icon: 'none' })
      }
    }
  }
}
</script>

<style scoped>
.vip-center {
  background: #F5F5F5;
  min-height: 100vh;
  padding-bottom: 140rpx;
}

/* VIP套餐选择 */
.vip-section {
  background: #FFF;
  padding: 40rpx 30rpx;
  margin-bottom: 20rpx;
  }

.vip-header {
  margin-bottom: 30rpx;
  position: relative;
}

.vip-title-wrap {
  display: inline-block;
  position: relative;
}

.vip-title {
  display: inline-block;
  position: relative;
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  padding-bottom: 12rpx;
}

.vip-title-bg {
  position: absolute;
  left: 0;
  bottom: 10rpx;
  width: 100%;
  height: 18rpx;
  pointer-events: none;
}

.vip-subtitle {
  display: block;
  font-size: 28rpx;
  color: #666;
}

.vip-plans {
  display: flex;
  gap: 20rpx;
}

.plan-item {
  flex: 1;
  background: #f2f4f3;
  border-radius: 20rpx;
  padding: 30rpx 20rpx;
  text-align: center;
  position: relative;
  border: 3rpx solid #f2f4f3;
  transition: all 0.3s ease;
  }

.plan-item.active {
  background: #fcf4f0;
  border: 3rpx solid #f8eae1;
  transform: scale(1.05);
  box-shadow: 0 8rpx 30rpx rgba(248, 234, 225, 0.3);
}

.plan-item.popular {
  flex: 1;
  /* background: linear-gradient(180deg, #fff7f3 0%, #ffffff 100%);
  border-color: #ffe9de; */
}

.plan-badge {
  position: absolute;
  top: -10rpx;
  right: -10rpx;
  background: linear-gradient(135deg, #FFD700, #FFA500);
  color: #FFF;
  font-size: 20rpx;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-weight: bold;
}

.plan-duration {
  font-size: 26rpx;
  font-weight: bold;
  color: #5c2b0f;
  margin-bottom: 15rpx;
}

.plan-price {
  display: flex;
  align-items: baseline;
  justify-content: center;
  margin-bottom: 10rpx;
}

.price-symbol {
  font-size: 24rpx;
  color: #5c2b0f;
  font-weight: bold;
}

.price-value {
  font-size: 44rpx;
  font-weight: bold;
  color: #5c2b0f;
}

.plan-original {
  margin-bottom: 15rpx;
}

.plan-original text {
  font-size: 22rpx;
  color: #5c2b0f;
  text-decoration: line-through;
}

.plan-desc {
  font-size: 22rpx;
  color: #5c2b0f;
  background: #e1e3e5;
  padding: 8rpx 18rpx;
  border-radius: 20rpx;
  margin-top: 10rpx;
}

.plan-item.active .plan-desc {
  background: #fef7f2;
}

/* VIP权益 */
.benefits-section {
  background: #FFF;
  padding: 30rpx;
  margin-bottom: 20rpx;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
}

.section-title { display: none; }

.benefits-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 24rpx;
}

.benefit-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.benefit-icon {
  width: 72rpx;
  height: 72rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 15rpx;
  box-shadow: 0 6rpx 16rpx rgba(255, 137, 100, 0.15);
}

.benefit-image {
  width: 72rpx;
  height: 72rpx;
}

.benefit-title {
  font-size: 26rpx;
  font-weight: bold;
  color: #999;
  margin-bottom: 8rpx;
}

.benefit-desc {
  font-size: 22rpx;
  color: #666;
  line-height: 1.4;
}

/* 最近开通VIP */
.recent-vips {
  background: #FFF;
  padding: 30rpx;
  margin-bottom: 20rpx;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
}

.vip-count {
  background: #FF6B6B;
  color: #FFF;
  font-size: 22rpx;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
}

.vips-list {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
  padding: 10rpx 0;
}

.vip-item {
  display: flex;
  flex-direction: row;
  align-items: center;
  padding: 10rpx 0;
}

@keyframes slideInUp {
  from {
    opacity: 0;
    transform: translateY(-30rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.vip-avatar {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  margin-right: 20rpx;
  background: #F5F5F5;
}

.vip-info { flex: 1; text-align: left; }

.vip-message { font-size: 26rpx; color: #333; }
.vip-plan-highlight { color: #f4b024; }

.vip-plan {
  background: linear-gradient(135deg, #FF6B6B, #FF8E8E);
  color: #f4b024;
  font-size: 22rpx;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  background: #fff;
  border: 1rpx solid #f4b024;
}

/* 购买按钮 */
.purchase-section {
  position: fixed;
  bottom: 30rpx;
  left: 30rpx;
  right: 30rpx;
  background: #2a1601;
  padding: 0;
  border-radius: 60rpx;
  box-shadow: 0 12rpx 40rpx rgba(0, 0, 0, 0.12);
  z-index: 100;
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.selected-plan-info {
  display: flex;
  align-items: center;
  flex: 1;
  color: #fff;
  padding: 16rpx 24rpx;
  border-radius: 44rpx;
}

.selected-text {
  font-size: 26rpx;
  color: #fff;
}

.selected-price {
  font-size: 32rpx;
  font-weight: bold;
  color: #fff;
  margin-left: 6rpx;
}

.purchase-btn {
  background: linear-gradient(180deg, #f7c8ad, #e6b391);
  color: #333;
  text-align: center;
  padding: 22rpx 36rpx;
  border-radius: 60rpx;
  font-size: 32rpx;
  font-weight: bold;
}

.purchase-btn:active {
  transform: scale(0.98);
  box-shadow: 0 4rpx 15rpx rgba(236, 200, 171, 0.4);
}

/* 响应式适配 */
@media screen and (max-width: 375px) {
  .vip-plans {
    flex-direction: column;
  }
  
  .plan-item {
    margin-bottom: 15rpx;
  }
  
  .benefits-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style>
